<template>
  <div class="products">
    <div class="header">
      <h1>{{ pageTitle }}</h1>
      <div class="filter-bar">
        <el-select v-model="categoryId" placeholder="选择分类" class="filter-select">
          <el-option label="全部分类" :value="''"></el-option>
          <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
        </el-select>
        <el-input v-model="keyword" placeholder="搜索商品" class="search-input" @keyup.enter="searchProducts">
          <template #append>
            <el-button icon="Search" @click="searchProducts"></el-button>
          </template>
        </el-input>
      </div>
    </div>
    
    <div class="product-list">
      <el-card 
        v-for="product in productList" 
        :key="product.id" 
        class="product-card"
        @click="handleProductClick(product.id)"
      >
        <img :src="product.imageUrl" alt="商品图片" class="product-image">
        <div class="product-info">
          <h3 class="product-title">{{ product.name }}</h3>
          <p class="product-desc">{{ product.description }}</p>
          <p class="product-price">¥{{ formatPrice(product.price || 0) }}</p>
          <div class="product-stock">库存: {{ product.stock }}</div>
          <el-button type="primary" size="small" class="add-to-cart-btn">
            加入购物车
          </el-button>
        </div>
      </el-card>
    </div>
    
    <div class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { productService } from '../services/productService'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 商品列表数据
const productList = ref([])

// 分类数据
const categories = ref([])

// 筛选条件
const categoryId = ref('')
const keyword = ref('')

// 计算属性：页面标题
const pageTitle = computed(() => {
  if (categoryId.value) {
    const currentCategory = categories.value.find(cat => cat.id == categoryId.value)
    return currentCategory ? currentCategory.name : '商品列表'
  } else if (keyword.value) {
    return `搜索: ${keyword.value}`
  }
  return '商品列表'
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 处理401错误
const handleUnauthorizedError = () => {
  ElMessageBox.confirm(
    '您的登录已过期，请重新登录',
    '登录已过期',
    {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    router.push('/login')
  }).catch(() => {
    // 用户取消操作，不做任何处理
  })
}

// 加载分类数据
const loadCategories = async () => {
  try {
    const result = await productService.getCategories()
    console.log('分类数据原始结果:', result)
    console.log('分类数据类型:', typeof result)
    if (Array.isArray(result)) {
      console.log('分类数组内容:', result)
      result.forEach((cat, index) => {
        console.log(`分类${index}:`, cat, 'ID:', cat.id, '名称:', cat.name)
      })
    }
    categories.value = result || []
    console.log('设置后的分类数据:', categories.value)
  } catch (error) {
    console.error('加载分类失败:', error)
    if (error.statusCode === 401) {
      handleUnauthorizedError()
    } else {
      ElMessage.error('加载分类失败')
    }
  }
}

// 加载商品列表数据
const loadProducts = async () => {
  try {
    let result
    
    // 如果选择了分类，优先按分类获取商品
    if (categoryId.value) {
      result = await productService.getProductsByCategory(categoryId.value, currentPage.value, pageSize.value)
    } else if (keyword.value && keyword.value.trim()) {
      // 如果有关键词，使用搜索API
      result = await productService.searchProducts(keyword.value, currentPage.value, pageSize.value)
    } else {
      // 否则使用普通获取商品列表API
      result = await productService.getProducts(currentPage.value, pageSize.value)
    }
    
    console.log('商品列表结果:', result)
    
    // 检查返回的数据结构
    let products = []
    let totalCount = 0
    
    if (Array.isArray(result)) {
      // 如果直接返回数组
      products = result
      totalCount = result.length
    } else if (result && result.products) {
      // 如果返回的是分页对象，包含products字段
      products = result.products || []
      totalCount = result.total || 0
    } else if (result && result.data) {
      // 兼容旧的data字段格式
      products = result.data || []
      totalCount = result.total || 0
    }
    
    // 确保每个商品都有默认值，防止渲染错误
    productList.value = products.map(product => ({
      id: product.id || '',
      name: product.name || '未知商品',
      price: Number(product.price) || 0,
      description: product.description || '暂无描述',
      stock: Number(product.stock) || 0,
      imageUrl: product.imageUrl || '/placeholder.jpg',
      category: product.category || null
    }))
    
    total.value = totalCount
    
    console.log('处理后的商品列表:', productList.value)
  } catch (error) {
    console.error('加载商品列表失败:', error)
    if (error.statusCode === 401) {
      handleUnauthorizedError()
    } else {
      ElMessage.error('加载商品列表失败')
    }
    
    // 设置空数组，防止渲染错误
    productList.value = []
    total.value = 0
  }
}

// 搜索商品
const searchProducts = () => {
  currentPage.value = 1
  loadProducts()
}

// 处理分类变化
watch(categoryId, () => {
  currentPage.value = 1
  loadProducts()
})

// 监听路由参数变化，当搜索关键词变化时重新加载商品列表
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword !== undefined) {
    keyword.value = decodeURIComponent(newKeyword)
    currentPage.value = 1
    loadProducts()
  }
})

// 监听路由参数变化，当分类ID变化时重新加载商品列表
watch(() => route.query.categoryId, (newCategoryId) => {
  if (newCategoryId !== undefined) {
    // 使用数字类型，与API返回的分类ID类型保持一致
    categoryId.value = Number(newCategoryId)
    currentPage.value = 1
    loadProducts()
  }
})

// 计算属性：获取当前分类对象
const currentCategory = computed(() => {
  if (!categoryId.value) return null
  return categories.value.find(cat => cat.id == categoryId.value)
})

// 处理分页变化
const handleSizeChange = (size) => {
  pageSize.value = size
  loadProducts()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  loadProducts()
}

// 处理商品点击
const handleProductClick = (productId) => {
  router.push(`/product/${productId}`)
}

// 格式化价格显示
const formatPrice = (price) => {
  if (!price) return '0.00'
  
  // 如果价格是数字
  if (typeof price === 'number') {
    return price.toFixed(2)
  }
  
  // 如果价格是字符串，尝试转换为数字
  if (typeof price === 'string') {
    const num = parseFloat(price)
    if (!isNaN(num)) {
      return num.toFixed(2)
    }
    return price
  }
  
  // 如果价格是对象，尝试获取parsedValue或value
  if (typeof price === 'object') {
    if (price.parsedValue !== undefined) {
      return price.parsedValue.toFixed(2)
    }
    if (price.value !== undefined) {
      return price.value.toFixed(2)
    }
  }
  
  return '0.00'
}

// 页面加载时初始化数据
onMounted(() => {
  loadCategories()
  
  // 从URL参数中获取搜索关键词
  if (route.query.keyword) {
    keyword.value = decodeURIComponent(route.query.keyword)
  }
  
  // 从URL参数中获取分类ID
  if (route.query.categoryId) {
    // 使用数字类型，与API返回的分类ID类型保持一致
    categoryId.value = Number(route.query.categoryId)
  }
  
  loadProducts()
})
</script>

<style scoped>
.products {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.header h1 {
  font-size: 28px;
  margin-bottom: 20px;
}

.filter-bar {
  display: flex;
  gap: 20px;
  align-items: center;
}

.filter-select {
  width: 200px;
}

.search-input {
  width: 300px;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.product-card {
  /* height: 400px; 注释掉固定高度，让卡片根据内容自适应 */
  cursor: pointer;
  transition: all 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
}

.product-info {
  padding: 10px;
}

.product-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  font-size: 18px;
  color: #ff4d4f;
  margin-bottom: 10px;
}

.product-stock {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.add-to-cart-btn {
  float: right;
}

.pagination {
  margin-top: 30px;
  text-align: center;
}
</style>